package pcloud.org.server.resource;

import java.io.File;
import java.io.FileNotFoundException;

import javax.servlet.http.HttpServletRequest;

import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.PUT;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.UploadAdaptor;

import pcloud.org.server.component.FileComponent;
import pcloud.org.server.model.FileInfo;

@At(FilesResource.PATH)
@IocBean
public class FilesResource
{
	public static final String PATH = "/files";
	private static final Log log = Logs.getLog(FilesResource.class);
	@Inject
	private FileComponent fileComponent;

	@At("/*")
	@PUT
	@AdaptBy(type = UploadAdaptor.class, args = {"${app.root}/tmpFile"} )
	public FileInfo uploadFile(String path, @Param("..") FileInfo fileInfo, @Param("fileContent") File file,
			HttpServletRequest request) throws FileNotFoundException
	{
		String absolutePath = request.getServletPath();
		log.info("REQUEST upload '" + absolutePath + "'");

		FileInfo responseInfo = fileComponent.update(absolutePath, fileInfo, file);

		log.info("RESPONSE upload '" + absolutePath + "'\r\n--" + Json.toJson(responseInfo));
		return responseInfo;
	}

	@At("/*")
	@GET
	@Ok("raw:stream")
	public File downloadFile(String path, HttpServletRequest request, AdaptorErrorContext errCtx)
			throws FileNotFoundException
	{
		String absolutePath = request.getServletPath();
		log.info("REQUEST download '" + absolutePath + "'");

		File file = fileComponent.getPrivateFile(absolutePath);
		log.info("RESPONSE download '" + absolutePath + "'\r\n--file length: " + file.length());
		return file;
	}

	// 整合了文件下载与获取文件信息的方法
	// @At("/*")
	// @GET
	// public View getResource(String path, boolean download, HttpServletRequest
	// request, AdaptorErrorContext errCtx)
	// {
	// String absolutePath = request.getServletPath();
	// //download=false 表示不下载,只获取文件信息
	// if (!download) {
	// FileInfo responseInfo = fileComponent.get(absolutePath);
	// if (!responseInfo.exists()) {
	// return new ViewWrapper(new HttpStatusView(404),
	// "File resouce doesn't exist!");
	// }
	// return new ViewWrapper(new UTF8JsonView(JsonFormat.nice()),
	// responseInfo);
	// }
	//		
	// //download=true 表示下载文件
	// try {
	//			
	// File file = fileComponent.getPrivateFile(absolutePath);
	// return new ViewWrapper(new RawView("stream"), file);
	// } catch (FileNotFoundException e) {
	// return new ViewWrapper(new HttpStatusView(404),
	// "File resouce doesn't exist!");
	// }
	// }

}
